package top.glkj.hms.utils;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20190711.models.SendStatus;
import lombok.extern.slf4j.Slf4j;
import top.glkj.hms.config.SmsConfig;
import top.glkj.hms.exception.DefineException;


/**
 * @author : xgl
 * @version : 0.0.1
 * @date :2020/9/2 0:53
 */
@Slf4j
public class SendSmsUtil {
    private static final SendSmsRequest REQ = new SendSmsRequest();

    private static SmsClient getSms() {
        Credential cred = new Credential(SmsConfig.SECRET_ID, SmsConfig.SECRET_KEY);
        return new SmsClient(cred, "");
    }

    private static void init() {
        REQ.setSmsSdkAppid(SmsConfig.SMS_SDK_APP_ID);
        REQ.setSign(SmsConfig.SIGN);
    }

    public static String send(String phone, String templateId, String[] msg) throws DefineException {
        init();
        REQ.setTemplateID(templateId);
        REQ.setTemplateParamSet(msg);
        REQ.setPhoneNumberSet(new String[]{"+86" + phone});
        SendSmsResponse res = null;
        try {
            res = getSms().SendSms(REQ);
        } catch (TencentCloudSDKException e) {
            throw new DefineException("短信发送异常：原因{" + e.getMessage() + "}");
        }
        return SendSmsResponse.toJsonString(res);
    }

    public static String send(String[] phones, String templateId, String[] msg) throws DefineException {
        init();
        for (int i = 0; i < phones.length; i++) {
            phones[i] = String.format("+86%s", phones[i]);
        }
        REQ.setTemplateID(templateId);
        REQ.setTemplateParamSet(msg);
        REQ.setPhoneNumberSet(phones);
        SendSmsResponse res = null;
        try {
            res = getSms().SendSms(REQ);
        } catch (TencentCloudSDKException e) {
            throw new DefineException("短信发送异常：原因{" + e.getMessage() + "}");
        }

        return SendSmsResponse.toJsonString(res);
    }

    public static boolean send(String phone, String templateId, String msg) throws DefineException {
        init();
        REQ.setTemplateID(templateId);
        REQ.setTemplateParamSet(new String[]{msg});
        REQ.setPhoneNumberSet(new String[]{"+86" + phone});
        SendSmsResponse res = null;
        try {
            res = getSms().SendSms(REQ);
        } catch (TencentCloudSDKException e) {
            throw new DefineException("短信发送异常：原因{" + e.getMessage() + "}");
        }
        SendStatus sendStatus = res.getSendStatusSet()[0];
        log.info(sendStatus.getMessage());
        return "Ok".equals(sendStatus.getCode()) && "send success".equals(sendStatus.getMessage());
    }
}
